package com.helper.debugger.utils.httpserver;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import com.helper.debugger.R;

/*
清单配置
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<service
    android:name=".utils.httpserver.LocalHttpServerService"
    android:enabled="true"
    android:exported="false"
    android:foregroundServiceType="location|microphone"
    tools:ignore="ForegroundServicePermission" />
* */

public class LocalHttpServerService extends Service {
    private static final String CHANNEL_ID = "local_http_server";
    private static LocalHttpServer.StartedCallback callback;

    @SuppressLint("ObsoleteSdkInt")
    public static void start(Context context, LocalHttpServer.StartedCallback callback) {
        LocalHttpServerService.callback = callback;
        LocalHttpServerService.stop(context);
        //确保不和Activity关联，使用ApplicationContext
        Context appContext = context.getApplicationContext();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            appContext.startForegroundService(new Intent(appContext, LocalHttpServerService.class));
        } else {
            appContext.startService(new Intent(appContext, LocalHttpServerService.class));
        }
    }

    public static void stop(Context context) {
        //确保不和Activity关联，使用ApplicationContext
        Context appContext = context.getApplicationContext();
        appContext.stopService(new Intent(appContext, LocalHttpServerService.class));
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        log("前台服务 " + CHANNEL_ID + " 已启动");
        //升级为前台服务器，避免被系统回收
        createNotificationChannel();
    }

    @SuppressLint("ObsoleteSdkInt")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 升级为前台服务器，避免被系统回收
        if (!LocalHttpServer.isRunning() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("日志服务运行中...")
                    .setContentText("调试期间请勿结束后台进程")
                    .setSmallIcon(R.drawable.icon)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .build();
            startForeground(1, notification);
            LocalHttpServer.start(callback);
        }
        return START_STICKY;
    }

    @SuppressLint("ObsoleteSdkInt")
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel serviceChannel = new NotificationChannel(CHANNEL_ID, "HTTP服务通道", NotificationManager.IMPORTANCE_DEFAULT);
            NotificationManager manager = getSystemService(NotificationManager.class);
            manager.createNotificationChannel(serviceChannel);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        log("前台服务 " + CHANNEL_ID + " 已关闭");
        LocalHttpServer.stop();
    }

    private void log(String msg) {
        Log.i("[B]" + getClass().getSimpleName(), msg);
    }

    private void error(String msg) {
        Log.e("[B]" + getClass().getSimpleName(), msg);
    }
}
